package com.luxsoft.siipap.em.replica.utils;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

import org.dbunit.DatabaseUnitException;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.xml.FlatXmlDataSet;
import org.dbunit.operation.DatabaseOperation;
import org.springframework.core.io.Resource;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ConnectionCallback;
import org.springframework.util.Assert;

import com.luxsoft.siipap.service.ServiceLocator2;

/**
 * Utilerias para usar las librerias de DBUnit
 * 
 * @author Ruben Cancino
 *
 */
public final class DBUnitUtils {
	
	/**
	 * Inserta informacion en una o mas tablas con ayuda de DBUnit
	 * Util para perarar el estado incial de la base de datos antes de los tests
	 * 
	 * @param path
	 */
	public static void insertDataSet(final String path) throws Exception{
		final Resource rs=getResource(path);
		Assert.isTrue(rs.exists(),"Para insertar los datos debe existir el archivo: "+path);
		ServiceLocator2.instance();
		ServiceLocator2.getJdbcTemplate().execute(new ConnectionCallback(){

			public Object doInConnection(Connection con) throws SQLException,
					DataAccessException {
				IDatabaseConnection icon;
				try {
					icon = new DatabaseConnection(con);
					DatabaseOperation.INSERT.execute(icon, new FlatXmlDataSet(rs.getInputStream()));					
				} catch (IOException e) {
					e.printStackTrace();
				}catch (DatabaseUnitException e) {
					e.printStackTrace();
				}
				
				return null;
			}
			
		});
		
	}
	
	public static Resource getResource(String location){
		return ServiceLocator2.instance().getContext().getResource(location);
	}
	
	

}
